import { RbacMenuType } from '@/data/auth/menu';
import { useAdminPermissions } from '@/hooks/auth/usePermissions';
import { list } from '@/services/data';
import { Form, Transfer } from 'antd';
import React, { useEffect, useState } from 'react';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<RbacMenuType> & {
    targetKeys?: React.Key[];
  };

export type UpdateFormProps = {
  onSubmit: (values: FormValueType) => Promise<void>;
  values: Partial<RbacMenuType>;
};

const AddPermModal: React.FC<UpdateFormProps> = (props) => {
  const { adminPermissions }: any = useAdminPermissions();
  const transformedData =
    adminPermissions?.map(({ id, urlPerm, remark }: any) => ({
      name: `${urlPerm} ${remark}`,
      key: id,
    })) || [];

  const initialTargetKeys: React.Key[] | (() => React.Key[]) = [];
  const [form] = Form.useForm<FormValueType>();
  const [targetKeys, setTargetKeys] = useState<React.Key[]>(initialTargetKeys);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      const menuOrBtnId = props.values.id;
      const hasPermList = await list('/system/rbacPermissionMenuBtn', { menuOrBtnId });
      const hasPermIdList = hasPermList?.list?.map((btn: any) => btn.permissionId) || [];

      setTargetKeys(hasPermIdList);
    };
    if (props.values.id) fetchData();
  }, [props.values]);

  const handleOk = async () => {
    await props.onSubmit({ targetKeys });
  };

  const handleChange = (targetKeys: React.Key[]) => {
    setTargetKeys(targetKeys);
  };

  const handleSelectChange = (sourceSelectedKeys: React.Key[], targetSelectedKeys: React.Key[]) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  return (
    <Form form={form} initialValues={props.values}>
      <Transfer
        listStyle={{
          width: 500,
          height: 600,
        }}
        dataSource={transformedData}
        titles={['未得到权限', '已拥有权限']}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        onChange={handleChange}
        onSelectChange={handleSelectChange}
        render={({ name }) => `${name}`}
      />
    </Form>
  );
};

export default AddPermModal;
